package net.youpo.Market.Net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import net.youpo.Market.MarketApplication;
import net.youpo.Market.R;
import net.youpo.Market.Util.ConstantsTable;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class HttpConnection {
    private final int TIMEOUT = 3000;// 设定超时时间
    private String uri = MarketApplication.getMarketAppContext().getResources()
            .getString(R.string.server_ip);// 获取服务器ip地址

    /**
     * 请求服务器响应
     * 
     * @param requestType
     *            请求类型 requestContent [类型，参数，类型，参数]
     */
    public String requestService(String requestType, String... requestContent) {
        String resultData = "";
        InputStreamReader in = null;
        HttpURLConnection urlConn = null;
        BufferedReader buffer = null;
        try {
            StringBuffer sBuffer = new StringBuffer();
            for (int n = 0; n < requestContent.length; n++) {
                if ((n + 1) % 2 == 0) {
                    sBuffer.append("=" + requestContent[n] + "&");
                } else {
                    sBuffer.append(requestContent[n]);
                }
            }
            URL url = new URL(uri
                    + requestType
                    + "?"
                    + sBuffer
                    + "num="
                    + MarketApplication.getMarketAppContext().getResources()
                            .getString(R.string.market_id));

            if (url != null) {
                urlConn = (HttpURLConnection) url.openConnection();
                urlConn.setConnectTimeout(TIMEOUT);// 设置超时时间

                try {
                    in = new InputStreamReader(urlConn.getInputStream());
                } catch (ConnectException e) {
                    Log.e(ConstantsTable.LOG_TAG, "服务器宕机了...");
                    return resultData;
                }
                buffer = new BufferedReader(in);
                String inputLine = null;

                while ((inputLine = buffer.readLine()) != null) {
                    resultData += inputLine + "\n";
                }
                urlConn.disconnect();
                Log.d("H3c", resultData);
            }
        } catch (MalformedURLException e) {
            Log.e(ConstantsTable.LOG_TAG, "域名无法解析");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (buffer != null) {
                    buffer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultData;
    }

    /**
     * 请求服务器响应
     * 
     * @param requestType
     *            请求类型 requestContent [类型，参数，类型，参数]
     */
    public String requestService2(String requestType, StringBuffer sBuffer) {
        String resultData = "";
        InputStreamReader in = null;
        HttpURLConnection urlConn = null;
        BufferedReader buffer = null;
        try {
            URL url = new URL(uri
                    + requestType
                    + "?"
                    + sBuffer
                    + "&num="
                    + MarketApplication.getMarketAppContext().getResources()
                            .getString(R.string.market_id));
            Log.e("resultJson", "result:" + url.toString());
            if (url != null) {
                urlConn = (HttpURLConnection) url.openConnection();
                urlConn.setConnectTimeout(TIMEOUT);// 设置超时时间

                try {
                    in = new InputStreamReader(urlConn.getInputStream());
                } catch (ConnectException e) {
                    Log.e(ConstantsTable.LOG_TAG, "服务器宕机了...");
                    return resultData;
                }
                buffer = new BufferedReader(in);
                String inputLine = null;

                while ((inputLine = buffer.readLine()) != null) {
                    resultData += inputLine + "\n";
                }
                urlConn.disconnect();
                Log.d("H3c", resultData);
            }
        } catch (MalformedURLException e) {
            Log.e(ConstantsTable.LOG_TAG, "域名无法解析");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (buffer != null) {
                    buffer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultData;
    }

    public Bitmap getNetworkBitmap(String httpUrl) {
        Bitmap bitmap = null;
        HttpGet httpRequest = new HttpGet(httpUrl);
        // 取得HttpClient 对象
        HttpClient httpclient = new DefaultHttpClient();
        try {
            // 请求httpClient ，取得HttpRestponse
            HttpResponse httpResponse = httpclient.execute(httpRequest);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 取得相关信息 取得HttpEntiy
                HttpEntity httpEntity = httpResponse.getEntity();
                InputStream is = httpEntity.getContent();
                bitmap = BitmapFactory.decodeStream(is);
                is.close();
            } else {
                Log.e(ConstantsTable.LOG_TAG, "连接失败!");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}
